<?php
defined ( 'SYSPATH' ) or die ( 'No direct access allowed.' );
/**
 *
 * @author z
 *        
 */
class Controller_warning extends Controller_Admin {

		
	public function before() 
	{
		 try{
     	 ACL::Required('purchase warning');
    	}catch(HTTP_Exception_403 $e){
      	$this->request->redirect(URL::base(true));
  	  }
    	parent::before();
	}

    /**
     * 最新的采购下单界面
     * @20140914
     */
    public function Action_index()
    {

        $this->title = __( '采购支持界面的按照最佳采购日期从近到远排列的sku报表（采购支持报表）' );

        set_time_limit ( 0 );

        $erp_user_id = Service_olduser::Get_old_user_by_new_id();
        $erp_user_id = isset($erp_user_id['id'])?$erp_user_id['id']:NULL;

        if(isset($_GET['sku']) and trim($_GET['sku']))
        {
            $skulists = Warningtmp::get_sku_warning(array(trim($_GET['sku'])));
        }
        elseif(isset($_GET['days']))
        {
            $type_arr = array(1,3,7);

            if(!in_array($_GET['days'],$type_arr ))
            {
                $this->request->redirect(url::base(true)."warning/indexnew?days=1");
            }

            $select = array();
            if(trim($_GET['days']) == 1)
            {
                $select['maxbest'] = 1;

            }
            elseif(trim($_GET['days']) == 3)
            {
                $select['maxbest'] = 4;
                $select['minbest'] = 1;
            }
            elseif (trim($_GET['days']) == 7)
            {
                $select['maxbest'] = 7;
                $select['minbest'] = 4;
            }

            $select['oper'] = $erp_user_id;

            $select['limit'] = 0;
            $select['offset'] = 0;
            $countall = count(Warningtmp::get_skuwarning_select($select));

            $pagination         = Pagination::factory(array(
                'items_per_page'  => 50,
                'total_items'     => $countall,
                'uri'	            => $this->request->uri(),
            ));
            $select['limit'] = $pagination->items_per_page;
            $select['offset'] = $pagination->_offset;

            $skulists = Warningtmp::get_skuwarning_select($select);
        }
        else
        {
            $this->request->redirect(url::base(true)."warning/index?days=1");
        }
        $skulists = Warningtmp::skudata($skulists);
        $lasttime = Warningtmp::get_lasttime();

        $view = View::factory ( 'warning/warningsku' );

        //结果集
        $view->set('skulists',$skulists);

        /**
         * 最近更新时间
         */
        $view->set('lasttime',isset($lasttime['updatatime'])?$lasttime['updatatime']:date('Y-m-d H:i:s'));

        //所有计税方式
        $view->set('showback',$_GET);
        $view->set('pagination',$pagination);
        $this->response->body ( $view );
    }


    /**
     * 新的系统下单
     */
    public function Action_indexnew()
    {

        $this->title = __( '系统下单' );

        set_time_limit ( 0 );

        $erp_user_id = Service_olduser::Get_old_user_by_new_id();
        $erp_user_id = isset($erp_user_id['id'])?$erp_user_id['id']:NULL;//var_dump($erp_user_id);exit;
        // $erp_user_id=NULL;

      if(isset($_GET['sku']) and trim($_GET['sku']))
      {
            $skulists = Service_Warninglist::warning_sku($erp_user_id,trim($_GET['sku']),true);

      }
      elseif(isset($_GET['days']))
        {
            $type_arr = array(1,3,7);

            if(!in_array($_GET['days'],$type_arr ))
            {
                $this->request->redirect(url::base(true)."warning/indexnew?days=1");
            }

            $select = array();
            if(trim($_GET['days']) == 1)
            {
                $select['maxbest'] = 1;
            }
            elseif(trim($_GET['days']) == 3)
            {
                $select['maxbest'] = 4;
                $select['minbest'] = 1;
            }
            elseif (trim($_GET['days']) == 7)
            {
                $select['maxbest'] = 7;
                $select['minbest'] = 4;
            }

            $select['oper'] = $erp_user_id;

            $select['limit'] = 0;
            $select['offset'] = 0;
            $countall = count(Warningtmp::get_skuwarning_select($select));

            $pagination         = Pagination::factory(array(
                'items_per_page'  => 50,
                'total_items'     => $countall,
                'uri'	            => $this->request->uri(),
            ));
            $select['limit'] = $pagination->items_per_page;
            $select['offset'] = $pagination->_offset;

            $skulists = Warningtmp::get_skuwarning_select($select);
            $skulists = Warningtmp::skudata($skulists);
            $lasttime = Warningtmp::get_lasttime();
        }
        else
        {
            $this->request->redirect(url::base(true)."warning/indexnew?days=1");
        }
        $skulists = Warningtmp::skudata($skulists);
        $lasttime = Warningtmp::get_lasttime();

        $tax_ways = Service_warning::get_tax_ways();
        $pay_ways = Service_warning::get_pay_ways();

        $view = View::factory ( 'warning/warningnew' );

        //结果集
        $view->set('skulists',$skulists);

        /**
         * 最近更新时间
         */
        $view->set('lasttime',isset($lasttime['updatatime'])?$lasttime['updatatime']:date('Y-m-d H:i:s'));

        //所有计税方式
        $view->set('tax_ways',$tax_ways);
        $view->set('pay_ways',$pay_ways);
        $view->set('showback',$_GET);
        $view->set('pagination',$pagination);
        $this->response->body ( $view );
    }

	/**
	 * 根据预警生成采购单处理
	 * 
	 */
	public function Action_warningaddpurchase()
	{
		// var_dump($_POST);exit;
		//有选择SKU才会添加
		if(isset($_POST) and isset($_POST['selectnum']))
		{
//			$a=20%90;
//			echo $a;
//			echo "<pre>";
//			print_r($_POST);
//			echo "</pre>";
//			exit();
			$count = 0;
			$purchasedetail_add = new Service_purchaseadd();

			foreach ($_POST['selectnum'] as $id)
			{
				$purchasedetails = array();
				 
				if(!isset($_POST['supplier_id'][$id])
					or $_POST['supplier_id'][$id] == 0
					or !isset($_POST['sku'][$id]) )
				{
					continue;
				}

				//SKU
				$purchasedetails['sku'] = $_POST['sku'][$id];
				
 				//名称
				$purchasedetails['sku_name'] = $_POST['sku_name'][$id];
				

				//供应商
 				$purchasedetails['supplier'] = $_POST['supplier_id'][$id];
				
 				//价格
 				$purchasedetails['single_price'] = $_POST['single_price'][$id];

 				//付款方式
 				$purchasedetails['pay_way'] = $_POST['pay_way'][$id]; 				
				
 				//税率
				//$purchasedetails['tax_rate'] = $_POST['tax_rate'][$id];

				//计税方式
				$purchasedetails['tax_way'] = $_POST['tax_way'][$id];
				
				//采购数量
 				$purchasedetails['quantity'] = $_POST['quantity'][$id];
				
 				//运费
				$purchasedetails['transportation_expense'] = $_POST['transportation_expense'][$id];
				
 				//预警数量
				$purchasedetails['warning_quantity'] = $_POST['warning_quantity'][$id];
				
 				//备注
 				$purchasedetails['remark'] = $_POST['remark'][$id];
				
 				if($purchasedetail_add->add_purchaseorder_details($purchasedetails) > 0)
 				{
 					$count ++;
 				}
 			}

			Message::success('添加'.$count.'记录成功');
		}
		
		$url = isset($_POST['current_uri'])?$_POST['current_uri']:(url::base(true).'warning/indexnew');
		$this->request->redirect($url);
	}
	
	
	/**
	 * 获取供应商产品数据
	 */
	public function Action_getproviderproducts()
	{
		$result = false;
		if(isset($_POST['purchase']) 
			and isset($_POST['purchase']['sku'])
			and isset($_POST['purchase']['supplier_id']))
		{
//          -----------------------------------------kdw----------------------------------
//			$providerproductsinfo = DB::select('iproviderID','price','delivery','payment')
//									->from('erp_providerproducts')
//									->join('erp_provider')
//									->on('erp_providerproducts.iproviderID','=','erp_provider.id')
//									->where('erp_providerproducts.iproviderID','=',$_POST['purchase']['supplier_id'])
//									->where('erp_providerproducts.iproductID','LIKE',trim($_POST['purchase']['sku']))
//									->execute('readonlyerp')
//									->current();

            $providerproductsinfo=array();

            //获取供应商sku信息
            $suppliersku=Newerpclientapi::getSupplierSkuBy($_POST['purchase']['supplier_id'],trim($_POST['purchase']['sku']));
            $providerproductsinfo['iproviderID']=$_POST['purchase']['supplier_id'];
            $providerproductsinfo['price']=$suppliersku['price'];
            $providerproductsinfo['delivery']=$suppliersku['delivery'];

            //获取到供应商支付方式
            $sql="SELECT id,paywayname FROM payways WHERE
                            id=(SELECT payways_id FROM supplierpayaccount WHERE supplier_id=".$_POST['purchase']['supplier_id']." LIMIT 0,1)";
            $pay=DB::query(Database::SELECT,$sql)->execute('newerp')->current();
//          -----------------------------------------kdw-end------------------------------
			if($providerproductsinfo)
			{
				// $provider_info=array();
				$result['provider_id'] = $providerproductsinfo['iproviderID'];
				
				$result['price'] = $providerproductsinfo['price'];//价格
				
				$result['delivery'] = date('Y-m-d', strtotime('+'.ceil($providerproductsinfo['delivery']).'days'));//交期
				
				$result['paytype'] = 0;
//              -----------------------------------kdw---------------------------------
//				if(isset($providerproductsinfo['payment']) and $providerproductsinfo['payment'])
//				{

//                    $sql = "SELECT id,type FROM erp_pay_type WHERE trim(type) LIKE '%".$providerproductsinfo['payment']."%'";
//                    $pay_wals = DB::query(Database::SELECT,$sql)
//                    ->execute('readonlyerp')
//                    ->current();
//
//                    if(isset($pay_wals['id']))
//                    {
//					    $result['paytype'] = $pay_wals['id'];
//				    }
//				}

                $result['paytype']=$pay['id'];
//            -----------------------------------kdw-end-----------------------------
				// $result[] = $provider_info;
			}
		}
	
		echo json_encode($result);exit();
	}

	/**
	 * 获取供应商付款方式
	 */
	public function getpaytypeid()
	{
		
	}
	
	
	/*
	 * 获取已经存在的采购单
	 */
	public function Action_purchase_exist()
	{
		
		$exist_id = array();

		if(isset($_POST['purchase']) and count($_POST['purchase']) >0)
		{
			foreach ($_POST['purchase'] as $key => $detail) 
			{
				$purchase = DB::select(array('purchaseorder_details.purchaseorder_id','purchaseorder_id'))
								->from('purchaseorder_details')
								->join('purchaseorders')
								->on('purchaseorder_details.purchaseorder_id','=','purchaseorders.id')
								->where('purchaseorder_details.supplier','=',$detail['supplier_id'])
								->where('purchaseorder_details.sku','=',$detail['sku'])
								->where('purchaseorders.purchase_id','=',user::active_user()->id)
								->where('purchaseorders.status','=',10)
								->where('purchaseorders.createtype','=',2)
								->execute('newerp')
								->current();
				if($purchase)
				{
					$exist_id[] = array('sku'=>$detail['sku'],
										'purchaseorder_id' => $purchase['purchaseorder_id']);
				}
			}
		}

		if(!empty($exist_id))
		{
			echo json_encode($exist_id);exit;
		}
		else
		{
			echo json_encode(0);exit;
		}
	}

	/**
	 * 添加单个采购单SKU
	 */
	public function Action_warningaddpurchase_one()
	{
		$re = false;
		if(isset($_POST) 
			and isset($_POST['purchase']))
		{
			

			foreach ($_POST['purchase']as $key => $purchase) {

				if( isset($purchase) and $purchase)
				{


                    /**
                     * 标志该sku最近有操作
                     * 不需要显示
                     */
                    if(isset($purchase['sku']))
                    {
                        $result = Cache::instance()->get('result_');
                        if($result and array_key_exists($purchase['sku'],$result))
                        {
                            Cache::instance()->delete('result_');
                            unset($result[$purchase['sku']]);
                            Cache::instance()->set('result_',$result,60*60*24);
                        }
                        
                        Warningtmp::set_flag_($purchase['sku']);
                    }


				$purchasedetail_add = new Service_purchaseadd();
				$purchaseorder = array();
				$purchasedetails = array();


				//采购单信息
				$purchaseorder['supplier_id'] = isset($purchase['supplier_id'])?$purchase['supplier_id']:NULL;
// 				$purchaseorder['money'] = isset($purchase['money'])?$purchase['money']:NULL;
// 				$purchaseorder['remark'] = isset($purchase['remark'])?$purchase['remark']:NULL;
// 				$purchaseorder['transportation_expense'] = isset($purchase['transportation_expense'])?$purchase['transportation_expense']:NULL;
				
// 				$purchaseorder['purchaseorder_date'] = isset($purchase['purchaseorder_date'])?$purchase['purchaseorder_date']:date("Y-m-d h:i:s");
				$purchaseorder['purchaseid'] = isset($purchase['purchaseid'])?$purchase['purchaseid']:user::active_user()->id;
				$purchaseorder['createtype'] = 2;
				
				//采购单合并附加条件
				$purchaseorder['sku'] = isset($purchase['sku'])?$purchase['sku']:NULL;
				$purchaseorder['arrive_date'] = isset($purchase['arrive_date'])?$purchase['arrive_date']:NULL;
				$purchaseorder['pay_way'] = isset($purchase['pay_way'])?$purchase['pay_way']:NULL;
				
				//采购详情单信息
				$purchasedetails['sku'] = isset($purchase['sku'])?$purchase['sku']:NULL;
				$purchasedetails['sku_name'] = isset($purchase['sku_name'])?$purchase['sku_name']:NULL;
	 			$purchasedetails['supplier'] = isset($purchase['supplier_id'])?$purchase['supplier_id']:NULL;
	 			$purchasedetails['single_price'] = isset($purchase['price'])?$purchase['price']:NULL;
	 			$purchasedetails['prime_cost'] =  isset($purchase['prime_cost'])?$purchase['prime_cost']:NULL;
	 			$purchasedetails['pay_way'] = isset($purchase['pay_way'])?$purchase['pay_way']:NULL;
				$purchasedetails['tax_rate'] = isset($purchase['tax_rate'])?($purchase['tax_rate']/100):NULL; 
				$purchasedetails['tax_way'] = isset($purchase['tax_way'])?$purchase['tax_way']:NULL; 
	 			$purchasedetails['quantity'] = isset($purchase['quantity'])?$purchase['quantity']:NULL; 
	 			$purchasedetails['warning_quantity'] = isset($purchase['warning_quantity'])?$purchase['warning_quantity']:NULL; 
	 			$purchasedetails['arrive_date'] =isset($purchase['arrive_date'])?$purchase['arrive_date']:NULL; 	
				$purchasedetails['transportation_expense'] = isset($purchase['transportation_expense'])?$purchase['transportation_expense']:NULL;
	 			$purchasedetails['remark'] = isset($purchase['remark'])?$purchase['remark']:NULL; 	
	 			$purchasedetails['storage_position'] = isset($purchase['storage_position'])?$purchase['storage_position']:NULL;
	 			$purchasedetails['sku_standard'] = isset($purchase['sku_standard'])?$purchase['sku_standard']:NULL;
	 			$purchasedetails['money'] = isset($purchase['money'])?$purchase['money']:NULL;
	 			$purchasedetails['no_tax_money'] = isset($purchase['no_tax_money'])?$purchase['no_tax_money']:NULL;
	 			$purchasedetails['tax_money'] = isset($purchase['tax_money'])?$purchase['tax_money']:NULL;
	 			$purchasedetails['sku_unit'] = isset($purchase['sku_unit'])?$purchase['sku_unit']:NULL;
	 			
	 			$purchasedetails['remark'] .= "采购预警";
// 	 			$purchasedetails['details_date'] = date("Y-m-d h:i:s");

	 			$purchase_o = $purchasedetail_add->add_purchaseorder($purchaseorder);
	 			
	 			if($purchase_o)
	 			{
		 			$purchase_d = $purchasedetail_add->add_purchaseorder_details($purchasedetails);
		 			
		 			if(isset($purchase_d['purchaseorders']))
		 			{
		 				$re[] = array('sku'=>$purchasedetails['sku'],
		 					'purchaseorder_id'=>$purchase_d['purchaseorders']);
		 			}
	 			}
	 				
	 			unset($purchaseorder);
	 			unset($purchasedetails);
	 			unset($purchase_o);
	 			unset($purchase_d);
				}
			}
			

		}

		echo json_encode($re);exit;
	}

	//取消预警，更改是否预警状态
	public function Action_nowarning_one()
	{
		$re = false;
		
		if(isset($_POST['data']) and isset($_POST['status']))
		{

			foreach ($_POST['data'] as $sku)
			{
				$sql_string = "UPDATE product_attached SET warning_status = ".$_POST['status'];
				$sql_string .= " WHERE sku LIKE ";
				$sql_string .= '"'. trim($sku['sku']).'"';
				
				$up = DB::query(Database::UPDATE, $sql_string)
				->execute('readonlyerp'); 
				$re[] = $sku['sku'];

				if($_POST['status']==1)
				{
                    //不需要预警的sku
                    $result = Cache::instance()->get('result_');
                    if($result and array_key_exists($sku['sku'],$result))
                    {
                        Cache::instance()->delete('result_');
                        unset($result[$sku['sku']]);
                        Cache::instance()->set('result_',$result,60*60*24);
                    }

                    $skuinfo = Cache::instance()->get('skuinfo_');
                    if($skuinfo and array_key_exists($sku['sku'],$skuinfo))
                    {
                        Cache::instance()->delete('skuinfo_');
                        unset($skuinfo[$sku['sku']]);
                        Cache::instance()->set('skuinfo_',$skuinfo,60*60*24);
                    }


                    /**
                     * 标志该sku最近有操作
                     * 不需要显示
                     */
                    Warningtmp::set_flag_($sku['sku']);
				} 				
			}
		}
		
		echo json_encode($re);exit;
	}
	
	//显示预警的SKU
	public function Action_warning_sku_lists()
	{
		$this->title = __("不下单的SKU列表");
		//var_dump(ACL::check('purchase warning'));exit;
		if(ACL::check('purchase warning'))
		{
			$erp_user_id = Service_olduser::Get_old_user_by_new_id();
			$erp_user_id = isset($erp_user_id['id'])?$erp_user_id['id']:NULL;
		}
		$sku = DB::select()
		->from('product_attached')
		->join('erp_products_data')
		->on('product_attached.sku','=','erp_products_data.products_sku')
		->where('product_attached.warning_status','=',1);
		if($erp_user_id)
		{
			$sku = $sku->where('erp_products_data.oper','=',$erp_user_id);
		}
		
		if(isset($_GET['sku']) and $_GET['sku'])
		{
			$sku = $sku->where('product_attached.sku','=',trim($_GET['sku']));
		}
		$count = $sku;
		$count = $count->execute('readonlyerp')->count();
		//var_dump($count);exit;
		$pagination         = Pagination::factory(array(
				'items_per_page'  =>50,
				'total_items'     => $count,
				'uri'	            => $this->request->uri(),
		));
		
		$sku = $sku 
		->offset($pagination->_offset)
  		->limit($pagination->items_per_page)
		->execute('readonlyerp')
		->as_array();
		
		$view = View::factory('warning/nowarning');
		$view->set('skus',$sku);
		$view->set('sum',$count);
		$view->set('pagination',$pagination);
		$this->response->body($view);
	}


    /**
     * 手动更新数据信息
     */
    public function Action_flushwarninghandle()
    {

        $this->title = "手动更新数据";

        $flushabled = false;

        $lasttime = Warningtmp::get_lasttime();
        if(isset($lasttime['updatatime']))
        {
           $lasttime_m = strtotime('now') - strtotime($lasttime['updatatime']);

           //echo $lasttime_m;
            /**
             * 手动刷新数据间隔不能小于指定的时间
             * 默认为10min
             */
            if($lasttime_m > 60*5)
           {
               $flushabled = true;
           }
        }

        if($flushabled)
        {
            $skus = Warningtmp::flush_skus();
            Warningtmp::count_waring_to_db($skus);
            $lasttime = Warningtmp::get_lasttime();
        }

        $view = View::factory('warning/flush')->set('lasttime',isset($lasttime['updatatime'])?$lasttime['updatatime']:'0000-00-00');
        $this->response->body($view);
    }

    /**
     * 显示单个系统下单的详情
     */
    public function action_purchaseone()
    {
        $re         = array(
            'code' => 0,
            'msg'  => '',
            'view' => ''
        );
        $view       = View::factory('warning/warningsupplier');
        $re['view'] = $view->render();

        echo json_encode($re);
        exit;
    }

    /**
     * 单个SKU系统下单跳转到新的页面了
     */
    public function action_purchaseonesku()
    {
        $this->title = __('单个SKU系统下单');

        if(isset($_GET['sku']) and trim($_GET['sku'])){
            /**
             * 获取预警信息
             */
            $erp_user_id = Service_olduser::Get_old_user_by_new_id();
            $erp_user_id = isset($erp_user_id['id'])?$erp_user_id['id']:NULL;
            $skulists    = Warningtmp::get_sku_warning(array(trim($_GET['sku'])));
            $skulists = Warningtmp::skudata($skulists);

            $supplier_for_sku = Warningtmp::get_provider_lists(trim($_GET['sku']));


            $supplier_payways = $payways = Supplierbank::do_select(array('supplier_id' => $supplier_for_sku[0]['iproviderID'],'active_status'=>1));
        }
        $tax_ways = Service_warning::get_tax_ways();
        $view     = View::factory('warning/warningsupplier');
        $view->set('skulists',isset($skulists[0])?$skulists[0]:NULL);
        $view->set('supplier_for_sku',$supplier_for_sku);
        $view->set('supplier_payways',$supplier_payways);
        $view->set('payaccountinfos',$supplier_payways);
        $view->set('tax_ways',$tax_ways);
        $this->response->body($view);
    }


    /***
     * 根据供应商和SKU查询信息
     */
    public function action_supplierskuinfo()
    {
        $re_view = array();
        if($this->request->is_ajax() and isset($_POST['supplier_id']) and isset($_POST['sku'])){
            $payways  = Supplierbank::do_select(array('supplier_id' => $_POST['supplier_id'],'active_status'=>1));
            $contacts = Newerpclientapi::getSupplierContacts($_POST['supplier_id']);

            $contact_view = View::factory('purchase/suppliercontact');
            $contact_view->set('contacts_info',$contacts);
            $re_view['supplier_contanct'] = $contact_view->render();

            $payways_view = View::factory('purchase/supplierpayway');
            $payways_view->set('pay_ways',$payways);
            $re_view['supplier_payway'] = $payways_view->render();

            $bank_account_view = View::factory('purchase/supplierbankinfo');
            $bank_account_view->set('payaccountinfos',$payways);
            $re_view['supplier_paybank'] = $bank_account_view->render();

            $sku_info            = Newerpclientapi::getSupplierSkuBy($_POST['supplier_id'],$_POST['sku']);
            $re_view['sku_name'] = $sku_info['productname'];
            $re_view['price']    = $sku_info['price'];
            $re_view['nuit']     = $sku_info['nuit'];
            $re_view['delivery'] = $sku_info['delivery'];
        }

        echo json_encode($re_view);
        exit;
    }
}




